﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Worktool.CODE_Chris.DataSourceHelpers;
using Worktool.CODE_Chris.Forms.Fertigungsauftrag;
using Worktool.CODE_Chris.Forms.MaterialFlow;
using Worktool.CODE_Chris.SQL_DATA;

namespace Worktool
{
    public partial class DeliveryChain : Form
    {
        bool userSicht = false;
        bool filterPurch = false;
        bool filterStorage = false;
        bool filterEngineer = false;
        bool filterCharacteristics = false;
        bool filterBereitstellungHHkleinerLieferterminHH = false;
        bool filterBereitstellungWerftkleinerLieferfaehigkeitHH = false;
        bool filterBestelltAberNichtGeliefert = false;
        bool filterGelieferteWareHH = false;
        bool filtergelieferteWareMW = false;
        private SQL sql;
        private Boolean isInit = true;
        private String pkInstalledPrinters;
        private PrintDocument label;

        //Datumsfilter
        public String fBestellfreigabeVon = null, fBestellterminVon = null, fBestaetigterLieferterminVon = null, fWareneingangVon = null, fSollBereitstellungHHVon = null;
        public String fIstBereitstellungHHVon = null, fLieferterminAnWerftVon = null, fSollBereitstellungSchiffVon = null;
        public String fBestellfreigabeBis = null, fBestellterminBis = null, fBestaetigterLieferterminBis = null, fWareneingangBis = null, fSollBereitstellungHHBis = null;
        public String fIstBereitstellungHHBis = null, fLieferterminAnWerftBis = null, fSollBereitstellungSchiffBis = null;
        public Boolean f1IsActive = false, f2IsActive = false, f3IsActive = false, f4IsActive = false, f5IsActive = false, f6IsActive = false, f7IsActive = false, f8IsActive = false;

        private DeliveryChainHelper helper;

        public DeliveryChain()
        {
            InitializeComponent();
            this.Text = "Lieferkette: " + Login.currentDBName; 

            init();
        }

        private void init()
        {
            sql = new SQL();
            helper = new DeliveryChainHelper(dataGridView1, dataGridView2, dataGridView3, dataGridView4, this);

            sql.sendSQL("dbo.updateMaterialDetailExtended");

            ToolTip ttip = new ToolTip();
            ttip.SetToolTip(button19, "Filter zurücksetzen");

            fillElementsInit();

            fillTablesInit();

            isInit = false;
        }

        #region Init
        private void fillTablesInit()
        {
            try
            {
                helper.getData1();
                helper.getData2();
                helper.getData3();
                helper.getData4();
            }
            catch (Exception e)
            {

            }
        }

        public void fillElementsInit()
        {
            isInit = true;
            //Fertigungsauftrag Combobox füllen
            try
            {
                String[,] fertigung = sql.receiveSQL("SELECT RIGHT('000000'+CAST(ISNULL(id,'') AS NVARCHAR(6)),6) AS ID FROM tbl_fertigungsauftrag");
                comboFertigung.Items.Clear();
                comboFertigung.Items.Add("Fertigungsauftrag öffnen");
                comboFertigung.DropDownHeight = 500;

                for (int a = 0; a < fertigung.GetLength(1); a++)
                {
                    comboFertigung.Items.Add(fertigung[0, a]);
                }
                comboFertigung.Refresh();
                comboFertigung.Text = "Fertigungsauftrag öffnen";

                //Fertigungsauftrag Filter Combobox füllen
                comboFertigungFilter.Items.Clear();
                comboFertigungFilter.Items.Add("Fertigungsauftrag filtern");
                comboFertigungFilter.DropDownHeight = 500;

                for (int a = 0; a < fertigung.GetLength(1); a++)
                {
                    comboFertigungFilter.Items.Add(fertigung[0, a]);
                }
                comboFertigungFilter.Refresh();
                comboFertigungFilter.Text = "Fertigungsauftrag filtern";

                //Sperre für Soll Bereitstellung HH auslesen
                readLock_SollBereitstellungHH();
            }
            catch (Exception e)
            {
                MessageBox.Show("Fehler beim Füllen der Fertigungsauftrag Combo-Boxen. Stacktrace:\r\n\r\n" + e.StackTrace, "Fehler");
            }

            // Drucker in das Auswahlfeld eintragen
            try
            {
                comboPrint.Items.Clear();
                comboPrint.DropDownHeight = 500;
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    pkInstalledPrinters = PrinterSettings.InstalledPrinters[i];
                    comboPrint.Items.Add(pkInstalledPrinters);
                }
                for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
                {
                    if (Login.labelPrinterName == PrinterSettings.InstalledPrinters[i])
                    {
                        comboPrint.Text = Login.labelPrinterName;
                    }
                }

                comboPrint.Text = comboPrint.Items[0].ToString();
            }
            catch (Exception e)
            {
                //MessageBox.Show("Fehler beim Füllen der Druck Combo-Box. Stacktrace:\r\n\r\n" + e.StackTrace, "Fehler");
            }


            isInit = false;
        }

        public void readLock_SollBereitstellungHH()
        {
            SQL.connectionString = Login.connectionMASTER;
            String[,] datum = sql.receiveSQL("SELECT [DeliveryChain_Sperre_SollBereitstellungHH] FROM TOOL_GeneralSettings");

            if (datum.GetLength(1) > 0) dateTimePickerSperre.Text = datum[0, 0]; else dateTimePickerSperre.Text = DateTime.Now.Date.ToShortDateString();

            SQL.connectionString = Login.connection;

            if (Login.user == "Hüttmann, Olaf" || Login.user == "Nowottny, Christopher") dateTimePickerSperre.Enabled = true;
        }

        public DateTimePicker getDatetimePicker_Sperre()
        {
            return dateTimePickerSperre;
        }

        private void DeliveryChain_Load(object sender, EventArgs e)
        {
            try
            {
                typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView1, new object[] { true });
                typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView2, new object[] { true });
                typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView3, new object[] { true });
                typeof(DataGridView).InvokeMember("DoubleBuffered", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetProperty, null, dataGridView4, new object[] { true });
            }
            catch (Exception)
            {

            }

        }
        #endregion

        #region Daten neu laden
        private void button10_Click(object sender, EventArgs e)
        {
            //resetFilters();
            reloadAllData();
        }

        public void reloadAllData()
        {
            Cursor.Current = Cursors.WaitCursor;
            this.Enabled = false;
            fillElementsInit();
            fillTablesInit();
            setMainFilters();
            this.Enabled = true;
            Cursor.Current = Cursors.Default;
        }
        #endregion

        #region Hauptmaske Fertigung
        private void buttonFertigung_Click(object sender, EventArgs e)
        {
            int isSelection = 0;
            List<FertigungsItem> fertigung = new List<FertigungsItem>();

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["Fertigungsauftrag"].Value != null)
                {
                    if (dataGridView1.Rows[a].Cells["Fertigungsauftrag"].Value.ToString() == "True")
                    {
                        DateTime? soll;
                        try
                        {
                            soll = DateTime.Parse(getFertigungValue(dataGridView1.Rows[a].Cells["Soll Bereitstellung HH"].Value.ToString()));
                        }
                        catch (Exception)
                        {
                            soll = null;
                        }

                        fertigung.Add(new FertigungsItem()
                        {
                            Detail_ID = Convert.ToInt32(getFertigungValue(dataGridView1.Rows[a].Cells["ID_MaterialDetailExtended"].Value.ToString())),
                            Manufacturer = getFertigungValue(dataGridView1.Rows[a].Cells["Manufacturer"].Value.ToString()),
                            Model = getFertigungValue(dataGridView1.Rows[a].Cells["Model"].Value.ToString()),
                            Venue = getFertigungValue(dataGridView1.Rows[a].Cells["Venue"].Value.ToString()),
                            PositionsID = getFertigungValue(dataGridView1.Rows[a].Cells["Positions_ID"].Value.ToString()),
                            JLM = getFertigungValue(dataGridView1.Rows[a].Cells["JLM"].Value.ToString()),
                            SollBereitstellung = soll
                        });
                        isSelection++;
                    }
                }
            }

            if (isSelection > 0)
            {
                FertigungsauftragPreMenu fertigungsauftrag = new FertigungsauftragPreMenu(fertigung, this, true, null);
                fertigungsauftrag.Show();
            }
            else
            {
                MessageBox.Show("Bitte wählen Sie zunächst Artikel aus, die in den Fertigungsauftrag eingebunden werden sollen. Dazu bitte ein Häkchen in der Spalte 'Fertigungsauftrag' setzen.", "Fehler");
            }
        }


        private String getFertigungValue(String value)
        {
            if (value == null) return ""; else return value;
        }

        public DataGridView getDataGrid()
        {
            return dataGridView1;
        }

        private void comboFertigung_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isInit)
            {
                if (comboFertigung.Text != "" && comboFertigung.Text != "Fertigungsauftrag öffnen")
                {
                    FertigungsauftragPreMenu fertigungsauftrag = new FertigungsauftragPreMenu(null, this, false, comboFertigung.Text);
                    fertigungsauftrag.Show();
                }
                else
                {
                    MessageBox.Show("Bitte wählen Sie zuerst einen Fertigungsauftrag aus.", "Fehler");
                }
            }
        }

        private void comboFertigungFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!isInit)
            {
                if (comboFertigungFilter.Text != "" && comboFertigungFilter.Text != "Fertigungsauftrag filtern")
                {
                    resetFilters();

                    String[,] ids = sql.receiveSQL("SELECT ID_MatDetailExt FROM tbl_fertigungsauftrag_matching WHERE ID_Fertigungsauftrag = " + comboFertigungFilter.Text);

                    String filter = "ID_MaterialDetailExtended = ";

                    for (int a = 0; a < ids.GetLength(1); a++)
                    {
                        if (a + 1 < ids.GetLength(1))
                        {
                            filter = filter + ids[0, a] + " OR ID_MaterialDetailExtended = ";
                        }
                        else
                        {
                            filter = filter + ids[0, a];
                        }
                    }

                    if (ids.GetLength(1) == 0) filter = "";

                    //vwcommLieferketteBindingSource1.Filter = string.Format(filter);
                    if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format(filter);
                }
                else
                {
                    MessageBox.Show("Bitte wählen Sie zuerst einen Fertigungsauftrag aus.", "Fehler");
                }
            }
        }

        private void button20_Click(object sender, EventArgs e)
        {
            if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
            isInit = true;
            comboFertigungFilter.Text = "Fertigungsauftrag filtern";
            comboFertigung.Text = "Fertigungsauftrag öffnen";
            isInit = false;
        }
        #endregion

        #region Hauptmaske Drucken
        private void buttonPrint_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView1.SelectedRows.Count != 0)
                {

                    // Zugehöriges Label ausdrucken
                    label = new PrintDocument();

                    if (comboPrint.Text != "TEC B-EV4-T" && comboPrint.Text != "TEC B-EV4-G")
                    {
                        PaperSize pS = new PaperSize("Custom Size", 620, 620);
                        label.DefaultPageSettings.PaperSize = pS;
                        label.PrinterSettings.PrinterName = comboPrint.Text;
                        label.PrinterSettings.DefaultPageSettings.PaperSize = pS;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                        label.Print();
                    }
                    else
                    {
                        //Labeldrucker mit Silber-Labels
                        label.PrinterSettings.PrinterName = comboPrint.Text;
                        label.PrintPage += new PrintPageEventHandler(label_PrintPage);
                        label.Print();
                    }
                }
                else
                {
                    MessageBox.Show("Bitte eine Zeile zum Drucken auswählen.", "Fehler");
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Fehler in button3_Click:\r\n\r\nFehlermeldung:\r\n" + ex.StackTrace.ToString());
            }
        }

        private void label_PrintPage(object sender, PrintPageEventArgs e)
        {
            try
            {
                String jlm = "JLM-Nr";
                String schiff_huellenNr = "";
                if (Login.currentDBName == "Hyperion")
                {
                    jlm = "Item-No";
                    String[,] temp = sql.receiveSQL("SELECT [Schiff_HuellenNr] FROM [tbl_systemData] WHERE ID = 1");
                    if (temp.GetLength(1) > 0) schiff_huellenNr = temp[0, 0];
                }

                if (comboPrint.Text != "TEC B-EV4-T" && comboPrint.Text != "TEC B-EV4-G")
                {
                    SolidBrush brush = new SolidBrush(Color.Black);
                    System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 8.0F, FontStyle.Bold);
                    //Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
                    //Image img;

                    e.Graphics.DrawString("Venue: " + dataGridView1.SelectedRows[0].Cells["Venue"].Value.ToString(), header, brush, 5, 5);
                    e.Graphics.DrawString("Manufacturer: " + dataGridView1.SelectedRows[0].Cells["Manufacturer"].Value.ToString(), header, brush, 5, 17);
                    e.Graphics.DrawString("Model: " + dataGridView1.SelectedRows[0].Cells["Model"].Value.ToString(), header, brush, 5, 29);
                    e.Graphics.DrawString(jlm+": " + dataGridView1.SelectedRows[0].Cells["JLM"].Value.ToString(), header, brush, 5, 41);
                    e.Graphics.DrawString("Position: " + dataGridView1.SelectedRows[0].Cells["Positions_ID"].Value.ToString(), header, brush, 5, 53);
                    if (Login.currentDBName == "Hyperion") e.Graphics.DrawString("Fitting-No: " + dataGridView1.SelectedRows[0].Cells["Fitting-No"].Value.ToString(), header, brush, 5, 65);
                    if (Login.currentDBName == "Hyperion" && schiff_huellenNr != "") e.Graphics.DrawString("Hüllennummer: " + schiff_huellenNr, header, brush, 5, 77);

                    // Logo
                    e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 200, 10, 30, 30);
                    // Barcode
                    //if (dataGridView1.SelectedRows[0].Cells["SeriennummerDataGridViewTextBoxColumn"].Value.ToString() != "")
                    //{
                    //    img = barcode128.Draw(dataGridView1.SelectedRows[0].Cells["SeriennummerDataGridViewTextBoxColumn"].Value.ToString(), 30);
                    //    e.Graphics.DrawImage(img, 5, 113);
                    //}
                }
                else
                {
                    //Labeldrucker mit Silber-Labels
                    SolidBrush brush = new SolidBrush(Color.Black);
                    System.Drawing.Font header = new System.Drawing.Font(FontFamily.GenericSansSerif, 8.0F, FontStyle.Bold);
                    //Code128BarcodeDraw barcode128 = BarcodeDrawFactory.Code128WithChecksum;
                    //Image img;

                    e.Graphics.DrawString("Venue: " + dataGridView1.SelectedRows[0].Cells["Venue"].Value.ToString(), header, brush, 5, 25);
                    e.Graphics.DrawString("Manufacturer: " + dataGridView1.SelectedRows[0].Cells["Manufacturer"].Value.ToString(), header, brush, 5, 37);
                    e.Graphics.DrawString("Model: " + dataGridView1.SelectedRows[0].Cells["Model"].Value.ToString(), header, brush, 5, 49);
                    e.Graphics.DrawString(jlm+": " + dataGridView1.SelectedRows[0].Cells["JLM"].Value.ToString(), header, brush, 5, 61);
                    e.Graphics.DrawString("Position: " + dataGridView1.SelectedRows[0].Cells["Positions_ID"].Value.ToString(), header, brush, 5, 73);
                    if (Login.currentDBName == "Hyperion") e.Graphics.DrawString("Fitting-No: " + dataGridView1.SelectedRows[0].Cells["Fitting-No"].Value.ToString(), header, brush, 5, 85);
                    if (Login.currentDBName == "Hyperion" && schiff_huellenNr != "") e.Graphics.DrawString("Hüllennummer: " + schiff_huellenNr, header, brush, 5, 97);

                    // Logo
                    e.Graphics.DrawImage(Worktool.Properties.Resources.ASC_Logo_quadratisch, 250, 0, 40, 40);
                    // Barcode
                    //if (dataGridView1.SelectedRows[0].Cells["SeriennummerDataGridViewTextBoxColumn"].Value.ToString() != "")
                    //{
                    //    img = barcode128.Draw(dataGridView1.SelectedRows[0].Cells["SeriennummerDataGridViewTextBoxColumn"].Value.ToString(), 40);
                    //    e.Graphics.DrawImage(img, 6, 148);
                    //}
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Fehler in label_PrintPage:\r\n\r\nFehlermeldung:\r\n" + ex.StackTrace.ToString());
            }
        }
        #endregion

        #region Exporteinstellungen
        private void button7_Click(object sender, EventArgs e)
        {
            dataGridView1.SelectAll();
            DataObject dataObj = dataGridView1.GetClipboardContent();
            if (dataObj != null)
                Clipboard.SetDataObject(dataObj);
            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            object misValue = System.Reflection.Missing.Value;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            xlexcel.Visible = true;
            xlWorkBook = xlexcel.Workbooks.Add(misValue);
            xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
            CR.Select();
            xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
            dataGridView1.ClearSelection();
        }

        private void button14_Click(object sender, EventArgs e)
        {
            dataGridView4.SelectAll();
            DataObject dataObj = dataGridView4.GetClipboardContent();
            if (dataObj != null) Clipboard.SetDataObject(dataObj);

            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();

                saveFile.Filter = "Excel-Format (*.xlsx)|*.xlsx";
                saveFile.FilterIndex = 2;
                saveFile.RestoreDirectory = true;

                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    File.Copy(Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\"+Login.currentDBName+"\\MaterialFlow\\DeliveryChain\\TemplateSummeExport.xlsx"), saveFile.FileName, true);

                    xlWorkBook = xlexcel.Workbooks.Open(saveFile.FileName);
                    xlexcel.Visible = true;
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[2, 1];
                    CR.Select();
                    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
                }

            }
            catch (ArgumentOutOfRangeException exx)
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show("Konnte Vorlage für Summe Schiff Export nicht finden.\r\n\r\nPfad, in dem die Datei erwartet wird:\r\n" + Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\"+Login.currentDBName+"\\MaterialFlow\\DeliveryChain\\TemplateSummeExport.xlsx"));
            }
            dataGridView4.ClearSelection();
        }

        private void button13_Click(object sender, EventArgs e)
        {
            dataGridView3.SelectAll();
            DataObject dataObj = dataGridView3.GetClipboardContent();
            if (dataObj != null) Clipboard.SetDataObject(dataObj);

            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();

                saveFile.Filter = "Excel-Format (*.xlsx)|*.xlsx";
                saveFile.FilterIndex = 2;
                saveFile.RestoreDirectory = true;

                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    File.Copy(Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\"+Login.currentDBName+"\\MaterialFlow\\DeliveryChain\\TemplateLagerExport.xlsx"), saveFile.FileName, true);

                    xlWorkBook = xlexcel.Workbooks.Open(saveFile.FileName);
                    xlexcel.Visible = true;
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[2, 1];
                    CR.Select();
                    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
                }

            }
            catch (ArgumentOutOfRangeException exx)
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show("Konnte Vorlage für Lager Export nicht finden.\r\n\r\nPfad, in dem die Datei erwartet wird:\r\n" + Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\" + Login.currentDBName + "\\MaterialFlow\\DeliveryChain\\TemplateLagerExport.xlsx"));
            }
            dataGridView3.ClearSelection();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            dataGridView2.SelectAll();
            DataObject dataObj = dataGridView2.GetClipboardContent();
            if (dataObj != null) Clipboard.SetDataObject(dataObj);

            Microsoft.Office.Interop.Excel.Application xlexcel;
            Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
            Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
            xlexcel = new Microsoft.Office.Interop.Excel.Application();
            try
            {
                SaveFileDialog saveFile = new SaveFileDialog();

                saveFile.Filter = "Excel-Format (*.xlsx)|*.xlsx";
                saveFile.FilterIndex = 2;
                saveFile.RestoreDirectory = true;

                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    File.Copy(Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\"+Login.currentDBName+"\\MaterialFlow\\DeliveryChain\\TemplateKaiExport.xlsx"), saveFile.FileName, true);

                    xlWorkBook = xlexcel.Workbooks.Open(saveFile.FileName);
                    xlexcel.Visible = true;
                    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
                    Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[2, 1];
                    CR.Select();

                    xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
                }
            }
            catch (ArgumentOutOfRangeException exx)
            {

            }
            catch (Exception ex)
            {
                MessageBox.Show("Konnte Vorlage für Kai Export nicht finden.\r\n\r\nPfad, in dem die Datei erwartet wird:\r\n" + Path.Combine(Login.dictSettings["netzwerkordner"], "Templates\\" + Login.currentDBName + "\\MaterialFlow\\DeliveryChain\\TemplateKaiExport.xlsx"));
            }
            dataGridView2.ClearSelection();
        }
        #endregion

        #region Filtereinstellungen
        private void button19_Click(object sender, EventArgs e)
        {
            resetFilters();
            setMainFilters();
        }

        private void resetFilters()
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox12.Text = "";
            textBox13.Text = "";

            //Datumsfilter auf null setzen
            fBestellfreigabeVon = null; fBestellterminVon = null; fBestaetigterLieferterminVon = null; fWareneingangVon = null; fSollBereitstellungHHVon = null;
            fIstBereitstellungHHVon = null; fLieferterminAnWerftVon = null; fSollBereitstellungSchiffVon = null;
            fBestellfreigabeBis = null; fBestellterminBis = null; fBestaetigterLieferterminBis = null; fWareneingangBis = null; fSollBereitstellungHHBis = null;
            fIstBereitstellungHHBis = null; fLieferterminAnWerftBis = null; fSollBereitstellungSchiffBis = null;
            f1IsActive = false; f2IsActive = false; f3IsActive = false; f4IsActive = false; f5IsActive = false; f6IsActive = false; f7IsActive = false; f8IsActive = false;

            button19.BackColor = Color.Gainsboro;
        }

        private void textBox11_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable4() != null) helper.getTable4().DefaultView.RowFilter = string.Format("Manufacturer LIKE '%{0}%' AND Model LIKE '%{1}%'", (Login.setFilterCharacters(textBox11.Text)), (Login.setFilterCharacters(textBox10.Text)));
        }

        private void textBox10_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable4() != null) helper.getTable4().DefaultView.RowFilter = string.Format("Manufacturer LIKE '%{0}%' AND Model LIKE '%{1}%'", (Login.setFilterCharacters(textBox11.Text)), (Login.setFilterCharacters(textBox10.Text)));
        }

        private void textBox9_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable3() != null) helper.getTable3().DefaultView.RowFilter = string.Format("ISNULL(CONVERT( Liefertermin, 'System.String'),'') LIKE '%{0}%' AND ISNULL(Packstück,'') LIKE '%{1}%'", (Login.setFilterCharacters(textBox8.Text)), (Login.setFilterCharacters(textBox9.Text)));
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable3() != null) helper.getTable3().DefaultView.RowFilter = string.Format("ISNULL(CONVERT( Liefertermin, 'System.String'),'') LIKE '%{0}%' AND ISNULL(Packstück,'') LIKE '%{1}%'", (Login.setFilterCharacters(textBox8.Text)), (Login.setFilterCharacters(textBox9.Text)));
        }

        private void button12_Click(object sender, EventArgs e)
        {
            if (filterBestelltAberNichtGeliefert)
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button12.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("[Liefertermin an Werft] IS NULL AND [Soll Bereitstellung Schiff] IS NOT NULL AND [Soll Bereitstellung Schiff] < '{0}' ", DateTime.Now);
                button12.BackColor = Color.Red;
            }
            filterBestelltAberNichtGeliefert = !filterBestelltAberNichtGeliefert;
        }

        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable2() != null) helper.getTable2().DefaultView.RowFilter = string.Format("ISNULL(CONVERT(Liefertermin, 'System.String'),'') LIKE '%{0}%' AND ISNULL(lieferscheinNummer,'') LIKE '%{1}%'", (Login.setFilterCharacters(textBox7.Text)), (Login.setFilterCharacters(textBox6.Text)));
        }

        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            if (helper.getTable2() != null) helper.getTable2().DefaultView.RowFilter = string.Format("ISNULL(CONVERT(Liefertermin, 'System.String'),'') LIKE '%{0}%' AND ISNULL(lieferscheinNummer,'') LIKE '%{1}%'", (Login.setFilterCharacters(textBox7.Text)), (Login.setFilterCharacters(textBox6.Text)));
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (filtergelieferteWareMW)
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button9.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("[Liefertermin an Werft] IS NOT NULL AND Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button9.BackColor = Color.Red;
            }
            filtergelieferteWareMW = !filtergelieferteWareMW;
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (filterGelieferteWareHH)
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button8.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("[Wareneingang ASC] IS NOT NULL AND Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button8.BackColor = Color.Red;
            }
            filterGelieferteWareHH = !filterGelieferteWareHH;
        }

        private void button6_Click(object sender, EventArgs e)
        {
            if (filterBereitstellungWerftkleinerLieferfaehigkeitHH)
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button6.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("[Ist Bereitstellung HH] > [Soll Bereitstellung Schiff] AND [Ist Bereitstellung HH] > '{7}' AND Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)), DateTime.Now);
                button6.BackColor = Color.Red;
            }
            filterBereitstellungWerftkleinerLieferfaehigkeitHH = !filterBereitstellungWerftkleinerLieferfaehigkeitHH;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (filterBereitstellungHHkleinerLieferterminHH)
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));
                button5.BackColor = System.Drawing.Color.Gainsboro;
            }
            else
            {
                if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = string.Format("bestaetigterLiefertermin > [Soll Bereitstellung HH] AND [Soll Bereitstellung HH] > '{7}' AND Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)), DateTime.Now);
                button5.BackColor = Color.Red;
            }
            filterBereitstellungHHkleinerLieferterminHH = !filterBereitstellungHHkleinerLieferterminHH;
        }

        //
        // Filter alle Userspalten
        //
        private void button1_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns["userbestellFreigabe"].Visible = !userSicht;
            dataGridView1.Columns["userbestellung"].Visible = !userSicht;
            dataGridView1.Columns["userbestaetigterLiefertermin"].Visible = !userSicht;
            dataGridView1.Columns["userwareneingang"].Visible = !userSicht;
            dataGridView1.Columns["userwareLieferSollHH"].Visible = !userSicht;
            dataGridView1.Columns["userwareLieferIstHH"].Visible = !userSicht;
            dataGridView1.Columns["userlieferungWerftIst"].Visible = !userSicht;
            dataGridView1.Columns["userlieferungSchiffSoll"].Visible = !userSicht;

            userSicht = !userSicht;
        }

        //
        // Filter alle Purchasingspalten
        //
        private void button4_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns["Bestelltermin"].Visible = filterPurch;
            dataGridView1.Columns["bestaetigterLiefertermin"].Visible = filterPurch;
            dataGridView1.Columns["Liefertermin an Werft"].Visible = filterPurch;
            dataGridView1.Columns["Lieferschein"].Visible = filterPurch;
            dataGridView1.Columns["laufende Nummer Auftrag"].Visible = filterPurch;
            dataGridView1.Columns["Auftragsnummer"].Visible = filterPurch;
            dataGridView1.Columns["Auftragsjahr"].Visible = filterPurch;
            dataGridView1.Columns["Kostenstelle MW"].Visible = filterPurch;
            dataGridView1.Columns["Bedarf MW"].Visible = filterPurch;

            if (filterPurch) { button4.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(224)))), ((int)(((byte)(192))))); } else { button4.BackColor = Color.Red; }
            filterPurch = !filterPurch;
        }

        //
        // Filter alle technische Ausprägung Spalten
        //
        private void button18_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns["Technische_Ausprägung_1"].Visible = filterCharacteristics;
            dataGridView1.Columns["Technische_Ausprägung_2"].Visible = filterCharacteristics;
            dataGridView1.Columns["Technische_Ausprägung_3"].Visible = filterCharacteristics;

            if (filterCharacteristics) { button18.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(192)))), ((int)(((byte)(255))))); } else { button18.BackColor = Color.Red; }
            filterCharacteristics = !filterCharacteristics;
        }

        //
        // Filter alle Storagespalten
        //
        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns["Wareneingang ASC"].Visible = filterStorage;
            dataGridView1.Columns["Ist Bereitstellung HH"].Visible = filterStorage;
            dataGridView1.Columns["Versandart"].Visible = filterStorage;
            dataGridView1.Columns["Packstück"].Visible = filterStorage;
            dataGridView1.Columns["Lagerort"].Visible = filterStorage;

            if (filterStorage) { button3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); } else { button3.BackColor = Color.Red; }
            filterStorage = !filterStorage;
        }

        //
        // Filter alle Engineerspalten
        //
        private void button2_Click(object sender, EventArgs e)
        {
            dataGridView1.Columns["bestellFreigabe"].Visible = filterEngineer;
            dataGridView1.Columns["Soll Bereitstellung HH"].Visible = filterEngineer;
            dataGridView1.Columns["Soll Bereitstellung Schiff"].Visible = filterEngineer;
            dataGridView1.Columns["Virtuelle Pack Nr."].Visible = filterEngineer;
            

            if (filterEngineer) { button2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); } else { button2.BackColor = Color.Red; }
            filterEngineer = !filterEngineer;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox5_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox12_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        private void textBox13_TextChanged(object sender, EventArgs e)
        {
            setMainFilters();
        }

        public void setMainFilters()
        {
            String filterString = string.Format("Venue LIKE '%{0}%' AND Manufacturer LIKE '%{1}%' AND Model LIKE '%{2}%' AND ISNULL(JLM,'') LIKE '%{3}%' AND ISNULL(Positions_ID,'')  LIKE '%{4}%' AND ISNULL(veredelungsSchritt,'')  LIKE '%{5}%' AND ISNULL(Anmerkungen,'')  LIKE '%{6}%' ", (Login.setFilterCharacters(textBox1.Text)), (Login.setFilterCharacters(textBox2.Text)), (Login.setFilterCharacters(textBox3.Text)), (Login.setFilterCharacters(textBox4.Text)), (Login.setFilterCharacters(textBox5.Text)), (Login.setFilterCharacters(textBox12.Text)), (Login.setFilterCharacters(textBox13.Text)));

            filterString += generateSingleFilterSQL("Bestellfreigabe",fBestellfreigabeVon, fBestellfreigabeBis, f1IsActive);
            filterString += generateSingleFilterSQL("Bestelltermin",fBestellterminVon, fBestellterminBis, f2IsActive);
            filterString += generateSingleFilterSQL("bestaetigterLiefertermin", fBestaetigterLieferterminVon, fBestaetigterLieferterminBis, f3IsActive);
            filterString += generateSingleFilterSQL("Wareneingang ASC", fWareneingangVon, fWareneingangBis, f4IsActive);
            filterString += generateSingleFilterSQL("Soll Bereitstellung HH", fSollBereitstellungHHVon, fSollBereitstellungHHBis, f5IsActive);
            filterString += generateSingleFilterSQL("Ist Bereitstellung HH", fIstBereitstellungHHVon, fIstBereitstellungHHBis, f6IsActive);
            filterString += generateSingleFilterSQL("Liefertermin an Werft", fLieferterminAnWerftVon, fLieferterminAnWerftBis, f7IsActive);
            filterString += generateSingleFilterSQL("Soll Bereitstellung Schiff", fSollBereitstellungSchiffVon, fSollBereitstellungSchiffBis, f8IsActive);

            setFilterButtonColor();

            if (helper.getTable1() != null) helper.getTable1().DefaultView.RowFilter = filterString;
        }

        private void setFilterButtonColor()
        {
            button19.BackColor = Color.Gainsboro;

            if (f1IsActive && (fBestellfreigabeVon != null || fBestellfreigabeBis != null)) button19.BackColor = Color.LightSalmon;
            if (f2IsActive && (fBestellterminVon != null || fBestellterminBis != null)) button19.BackColor = Color.LightSalmon;
            if (f3IsActive && (fBestaetigterLieferterminVon != null || fBestaetigterLieferterminBis != null)) button19.BackColor = Color.LightSalmon;
            if (f4IsActive && (fWareneingangVon != null || fWareneingangBis != null)) button19.BackColor = Color.LightSalmon;
            if (f5IsActive && (fSollBereitstellungHHVon != null || fSollBereitstellungHHBis != null)) button19.BackColor = Color.LightSalmon;
            if (f6IsActive && (fIstBereitstellungHHVon != null || fIstBereitstellungHHBis != null)) button19.BackColor = Color.LightSalmon;
            if (f7IsActive && (fLieferterminAnWerftVon != null || fLieferterminAnWerftBis != null)) button19.BackColor = Color.LightSalmon;
            if (f8IsActive && (fSollBereitstellungSchiffVon != null || fSollBereitstellungSchiffBis != null)) button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox1.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox2.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox3.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox4.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox5.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox12.Text) != "") button19.BackColor = Color.LightSalmon;
            if (Login.setFilterCharacters(textBox13.Text) != "") button19.BackColor = Color.LightSalmon;
        }

        private String generateSingleFilterSQL(String columnName, String value1, String value2, Boolean active)
        {
            
            if (!active) return "";

            String returnValue = "";



            if (value1 != null && value2 != null)
            {
                returnValue = "AND [" + columnName + "] >= '" + convertDate(value1) + "' AND [" + columnName + "] <= '" + convertDate(value2) + "' ";
            }
            else if (value1 != null)
            {
                returnValue = "AND [" + columnName + "] >= '" + convertDate(value1) + "' ";
            }
            else if (value2 != null)
            {
                returnValue = "AND [" + columnName + "] <= '" + convertDate(value2) + "' ";
            }

            return returnValue;
        }

        private String convertDate(String oldDate)
        {
            String newDate = "";

            newDate = oldDate.Substring(6, 4) + "-" + oldDate.Substring(3, 2) + "-" + oldDate.Substring(0, 2);

            return newDate;
        }

        #endregion

        #region Diverse Methoden
        public DeliveryChainHelper getHelper()
        {
            return helper;
        }
        #endregion

        private void button21_Click(object sender, EventArgs e)
        {
            DeliveryChainFilter chainFilter = new DeliveryChainFilter(this);
            chainFilter.ShowDialog();
        }

        private void dateTimePickerSperre_ValueChanged(object sender, EventArgs e)
        {
            if(!isInit)
            {
                SQL.connectionString = Login.connectionMASTER;
                sql.sendSQL("UPDATE TOOL_GeneralSettings SET [DeliveryChain_Sperre_SollBereitstellungHH] = '" + dateTimePickerSperre.Text + "'");
                SQL.connectionString = Login.connection;
            }
        }
    }
}
